import React, { Component } from 'react';
import { Button, Input, Empty, message, Spin, Icon } from 'antd';
import _ from 'lodash';
import EmptyDataImg from '@images/empty-data-blue.png';
import SwitchConfigModal from './components/switch-config-modal';
import SwtichCard from './components/switch-card';
import { getSwitchList, deleteSwitch, changeSwitchStatus } from '@api/switch';
import './index.less';

const { Search } = Input;
const prefixCls = 'switch-config';

class SwitchConfig extends Component {
  constructor(props) {
    super(props);
    this.state = {
      filter: {},
      modalVisibal: false,
      loading: false,
      confirmLoading: false,
      statusLoading: false,
      data: [],
      itemData: {}
    };
  }

  componentDidMount() {
    this.getSwitchList();
  }

  onSearchChange = e => {
    let { filter } = this.state;
    filter.search = e.target.value;
    this.setState({ filter });
  };

  wrapModalVisible = (visible, itemData = {}) => {
    this.setState({ modalVisibal: visible, itemData });
  };

  getSwitchList = () => {
    let filter = _.clone(this.state.filter);
    if (filter.search) {
      filter.search = filter.search.replace(/\\/g, '\\\\');
    }
    this.setState({ loading: true });
    getSwitchList(filter)
      .then(res => {
        const data = _.get(res, 'data.data.list', []);
        this.setState({ data, loading: false });
      })
      .catch(() => {
        message.error('获取列表失败');
        this.setState({ loading: false });
      });
  };

  afterSubmit = (toContinue = false) => {
    this.setState({ itemData: {}, modalVisibal: toContinue });
    this.getSwitchList();
  };

  deleteSwitch = item => {
    const id = _.get(item, '_id', '');
    const name = _.get(item, 'name', '');
    const ip = _.get(item, 'ip', '');
    deleteSwitch({ id, name, ip })
      .then(() => {
        message.success('删除成功');
        this.getSwitchList();
      })
      .catch(() => {
        message.error('删除失败');
      });
  };

  changeStatus = item => {
    let body = {};
    body.id = _.get(item, '_id');
    body.status = !_.get(item, 'status');
    body.name = _.get(item, 'name');
    body.ip = _.get(item, 'ip');

    this.setState({ statusLoading: true });
    changeSwitchStatus(body)
      .then(() => {
        message.success('修改成功');
        this.setState({ statusLoading: false }, this.getSwitchList);
      })
      .catch(() => {
        message.error('修改失败');
        this.setState({ statusLoading: false });
      });
  };

  render() {
    const {
      modalVisibal,
      confirmLoading,
      itemData,
      data,
      filter,
      loading,
      statusLoading
    } = this.state;

    return (
      <div className={prefixCls}>
        <Spin spinning={loading}>
          <div className={`${prefixCls}-page-title`}>交换机管理</div>
          <div className={`${prefixCls}-tips`}>
            <Icon type="info-circle" theme="twoTone" twoToneColor="#fc8e49" />
            &nbsp; 交换机配置：通过对交换机的 ARP 表进行分析，提取此交换机中记录的 IP
            作为新发现的资产自动补充到资产列表
          </div>
          <div className={`${prefixCls}-operation`}>
            <div>
              <Button type="primary" onClick={() => this.wrapModalVisible(true)}>
                添加交换机
              </Button>
              <SwitchConfigModal
                data={itemData}
                visible={modalVisibal}
                afterSubmit={this.afterSubmit}
                clearData={this.clearData}
                confirmLoading={confirmLoading}
                onClose={() => this.wrapModalVisible(false, {})}
              />
            </div>
            <div>
              <Search
                value={filter.search}
                enterButton
                placeholder="输入ip，交换机名称搜索"
                onChange={this.onSearchChange}
                onSearch={value => {
                  let search = value.toString();
                  filter.search = search;
                  this.setState({ filter }, this.getSwitchList);
                }}
              />
            </div>
          </div>
          {data.length ? (
            <div className={`${prefixCls}-page-content`}>
              {data.map(item => (
                <SwtichCard
                  key={_.get(item, '_id')}
                  data={item}
                  onEdit={() => this.wrapModalVisible(true, item)}
                  onDelete={() => this.deleteSwitch(item)}
                  statusLoading={statusLoading}
                  onStatus={() => this.changeStatus(item)}
                />
              ))}
            </div>
          ) : (
            <div>
              <Empty
                image={EmptyDataImg}
                imageStyle={{
                  margin: '0 24px',
                  height: 237
                }}
                description={
                  <div>
                    <span style={{ color: '#2A2B30' }}>您还未添加过交换机</span>
                    <p style={{ marginTop: 16, color: '#999EA8' }}>
                      通过配置交换机，帮助您监控探测资产存活
                    </p>
                  </div>
                }
              />
            </div>
          )}
        </Spin>
      </div>
    );
  }
}

export default SwitchConfig;
